package com.longcai.piaojia.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.DespositGridAdapter;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.DepositListGet;
import com.longcai.piaojia.conn.RechargeOrderNumGet;
import com.longcai.piaojia.fragment.MineFragment;
import com.longcai.piaojia.util.ClickUtil;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.util.WxPay;
import com.longcai.piaojia.widget.NoScrollGridView;
import com.module.zfb.PayAction;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilKeyBoard;
import com.zcx.helper.util.UtilToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2016/10/12.
 */
public class DepositActivity extends BaseActivity implements View.OnClickListener {

    public static final String RECHARGE_FILTER = "payRechargeBoradcast";

    // gridview 价格展示
    @BoundView(R.id.deposit_nsgv) private NoScrollGridView deposit_nsgv;
    //钱
    @BoundView(R.id.desposit_money_tv) private TextView desposit_money_tv;
    @BoundView(R.id.deposit_privilege_money_tv) private TextView deposit_privilege_money_tv;
    @BoundView(R.id.deposit_money_fill_et) private EditText deposit_money_fill_et;
    //提交按钮
    @BoundView(R.id.desposit_submit_tv) private TextView desposit_submit_tv;
    //微信
    @BoundView(R.id.desposit_wechat_rl) private RelativeLayout desposit_wechat_rl;
    @BoundView(R.id.desposit_wechat_check_sel_iv) private ImageView desposit_wechat_check_sel_iv;
    @BoundView(R.id.desposit_wechat_check_no_iv) private ImageView desposit_wechat_check_no_iv;
    //阿里
    @BoundView(R.id.desposit_alipay_rl) private RelativeLayout desposit_alipay_rl;
    @BoundView(R.id.desposit_alipay_check_sel_iv) private ImageView desposit_alipay_check_sel_iv;
    @BoundView(R.id.desposit_alipay_check_no_iv) private ImageView desposit_alipay_check_no_iv;

    private int payType = 0;//支付类型  0 微信支付  1 支付宝支付

    private List<DepositListGet.DespoistEntity> lists = new ArrayList<>();
    private DespositGridAdapter adapter;

    //支付三个参数
    private String presentMoney;
    private String title;
    private String payMoney;

    private int prePosition = -1;// -1 是 没选中状态


    //获取订单号接口
    private RechargeOrderNumGet rechargeOrderNumGet = new RechargeOrderNumGet(new AsyCallBack<String>(){

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {

            switch (payType) {

                case 0:

                    WxPay wxPay = new WxPay(DepositActivity.this);

                    wxPay.pay("友票充值", s, String.valueOf(Float.parseFloat(payMoney) * 100).replace(".0", ""), "2," + BaseApplication.BasePreferences.readUserId() + "," + presentMoney);// attach = 状态,会员ID,赠送金额 状态：1=支付 2=充值 赠送金额空为0

                    break;

                case 1:

                    PayAction payAction = new PayAction(DepositActivity.this) {
                        @Override
                        protected void onSuccess() {


                        }

                        @Override
                        protected void onEnd() {

                            onPaySuccessEnd();

                        }
                    };

                    try {

                        payAction.pay("友票充值", BaseApplication.BasePreferences.readUserId() + "," + presentMoney, s, Float.parseFloat(payMoney) + "", Conn.SERVICE + Conn.ALIPAY_RECHARGE_NOTIFYURL);// body=会员ID,赠送金额

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;

            }



        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            desposit_submit_tv.setEnabled(true);

            MyToast.show(context, toast, Toast.LENGTH_SHORT);
        }
    });

    //充值列表接口
    private DepositListGet depositListGet = new DepositListGet(new AsyCallBack<DepositListGet.DepositListGetEntity>(){


        @Override
        public void onSuccess(String toast, int type, DepositListGet.DepositListGetEntity depositListGetEntity) throws Exception {

            desposit_money_tv.setText(depositListGetEntity.wallet);

            deposit_privilege_money_tv.setText(depositListGetEntity.privilege);

            lists.addAll(depositListGetEntity.despoistEntityList);

            adapter.notifyDataSetChanged();

//            //刷新我的页面 余额数字
//            MineFragment.getUserAdvert getUserAdvert = (MineFragment.getUserAdvert) getAppCallBack(MineFragment.class);
//            getUserAdvert.updateMyPurse(depositListGetEntity.wallet);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.show(context, toast, Toast.LENGTH_SHORT);
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit);

        setBackTrue();

        setTitleName(getString(R.string.deposit_title_text));

        setRightName(getString(R.string.deposit_right_title_text), R.color.white, this);

        deposit_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(16));

        deposit_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));

        deposit_nsgv.setAdapter(adapter = new DespositGridAdapter(context, lists));

        deposit_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (prePosition != position) {

                    deposit_money_fill_et.setText("");

                    UtilKeyBoard.closeKeybord(deposit_money_fill_et, context);

                    payMoney = lists.get(position).money;

                    presentMoney = lists.get(position).present;

                    adapter.selPosition = position;

                    adapter.notifyDataSetChanged();

                    prePosition = position;

                }

            }
        });



        deposit_money_fill_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (prePosition != -1) {

                    adapter.selPosition = -1;//selposition  不大于0 刷新 就是不选中
                    adapter.notifyDataSetChanged();

                    prePosition = -1;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        registerReceiver(payRechargeBoradcast, new IntentFilter(RECHARGE_FILTER));

        depositListGet.user_id = BaseApplication.BasePreferences.readUserId();
        depositListGet.execute(this);

        desposit_wechat_rl.setOnClickListener(this);
        desposit_alipay_rl.setOnClickListener(this);
        desposit_submit_tv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.title_right_ll:

                startActivity(new Intent(DepositActivity.this, BalanceDetailActivity.class));

                break;

            case R.id.desposit_wechat_rl:

                if (desposit_wechat_check_no_iv.getVisibility() == View.VISIBLE) {

                    desposit_wechat_check_sel_iv.setVisibility(View.VISIBLE);
                    desposit_wechat_check_no_iv.setVisibility(View.GONE);
                    desposit_alipay_check_no_iv.setVisibility(View.VISIBLE);
                    desposit_alipay_check_sel_iv.setVisibility(View.GONE);

                    payType = 0;

                }

                break;

            case R.id.desposit_alipay_rl:

                if (desposit_alipay_check_no_iv.getVisibility() == View.VISIBLE) {

                    desposit_alipay_check_sel_iv.setVisibility(View.VISIBLE);
                    desposit_alipay_check_no_iv.setVisibility(View.GONE);
                    desposit_wechat_check_no_iv.setVisibility(View.VISIBLE);
                    desposit_wechat_check_sel_iv.setVisibility(View.GONE);

                    payType = 1;

                }

                break;

            case R.id.desposit_submit_tv:

                // 如果是 手动输入的话 支付的钱数就是 edittext的值  不是手动输入就是  gridview 选中那条的 钱数

                if (prePosition == -1) {

                    payMoney = deposit_money_fill_et.getText().toString().replace(" ", "");

                    presentMoney = "0";

                    if (TextUtils.isEmpty(payMoney)) {

                        MyToast.show(context, getString(R.string.warning_please_choose_or_fill_money), Toast.LENGTH_LONG);

                        return;
                    }

                }

                desposit_submit_tv.setEnabled(false);

                rechargeOrderNumGet.execute(this, false);

                break;


        }

    }



    public void onPaySuccessEnd() {

//        lists.clear();
//        depositListGet.user_id = BaseApplication.BasePreferences.readUserId();
//        depositListGet.execute(DepositActivity.this);


        finish();

        try {

            MineFragment.getUserAdvert getUserAdvert = (MineFragment.getUserAdvert) getAppCallBack(MineFragment.class);
            getUserAdvert.refreshInfo();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    BroadcastReceiver payRechargeBoradcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            onPaySuccessEnd();

        }
    };


}
